package com.snopy.url;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ReverseServlet
 * @description
 * @email 77912204@qq.com
 * @date 2022/08/01 12:10
 */
public class ReverseServlet extends HttpServlet {
    private static final long serialVersionUID = 5997770553125546026L;
    private static String message = "Error during Servlet processing";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            int len = req.getContentLength();
            byte[] input = new byte[len];
            ServletInputStream sin = req.getInputStream();
            int c,count = 0;
            while ((c = sin.read(input,count,input.length-count))!=-1){
                count += c;
            }
            sin.close();

            String inputString = new String(input);
            int index = inputString.indexOf("=");
            if (index == -1){
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write(message);
                resp.getWriter().close();
                return;
            }
            String value = inputString.substring(index + 1);
            String decodeString = URLDecoder.decode(value,"UTF-8");
            String reverseStr = new StringBuffer(decodeString).reverse().toString();
            resp.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
            writer.write(reverseStr);
            writer.flush();
            writer.close();
        }catch (IOException e){
            try {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write(e.getMessage());
                resp.getWriter().close();
            }catch (IOException ioe){}
        }

    }
}
